package com.captain.special.二叉树.中等;

import com.captain.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Des:
 * TODO 序列化与反序列化 *****
 *
 * @author XL
 * @Date 2022/5/19 11:10
 */
public class 序列化和反序列化二叉搜索树449 {
    public String serialize(TreeNode root) {
        StringBuilder builder = new StringBuilder();
        serialize(root, builder);
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }

    public void serialize(TreeNode node, StringBuilder builder) {
        //前序遍历,如果
        if (node == null) {
            builder.append("#");
            builder.append(",");
            return;
        }
        builder.append(node.val).append(",");
        serialize(node.left, builder);
        serialize(node.right, builder);
    }

    public TreeNode deserialize(String data) {
        String[] split = data.split(",");
        List<String> list = new LinkedList<>(Arrays.asList(split));
        return deserialize(list);
    }

    public TreeNode deserialize(List<String> dataList) {
        String valStr = dataList.get(0);
        if (valStr.equals("#")) {
            dataList.remove(0);
            return null;
        }
        TreeNode node = new TreeNode(Integer.valueOf(valStr));
        dataList.remove(0);
        //左
        node.left = deserialize(dataList);
        //右
        node.right = deserialize(dataList);
        return node;
    }
}
